/*******************************************************************************
* Copyright (c) 2010, 2017 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.MachiningRelation;
import com.qinyeit.serviceapp.entity.Material;
import com.qinyeit.serviceapp.entity.MaterialCategory;
import com.qinyeit.serviceapp.entity.enums.MaterialType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.dishes.MachiningRelationService;
import com.qinyeit.serviceapp.service.materials.MaterialCategoryService;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.SearchFilterHelper;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: MachiningRelationsController <br/>
 * Function: machiningRelation [加工关系明细] <br/>
 * date: 2019-01-24 13:52:07 <br/>
 *
 * @author 祁雪萍
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/machiningRelations")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "merchant_machiningRelation:read",name ="加工关系明细",deleteAble = false)
public class MachiningRelationsController extends BaseManagementController {

	@Autowired
	private MachiningRelationService machiningRelationService;

	@Autowired
    private MaterialService materialService;

    @Autowired
    private MaterialCategoryService materialCategoryService;

	private final String [] keys = {"id","productId","materialId","count","remark"};
    private final String [] materialKeys = {"id","pinyin","spell","no","name","category","goodsSpec","unit","minStock","maxStock","storeMode","purchaseNewPrice","consumeUnit","consumeUnit","consumeRates","orderPriceBom","orderType","stocktakeType","state", "uuid","digest"};


    @RequiresPermissions("merchant_machiningRelation:show")
    @PermissionInfo(code = "merchant_machiningRelation:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public Object index(Searchable searchable, String input, String material, Boolean hasCost){
        QyMap map= QyMap.NEW();
        Page<Map<String, Object>> list=machiningRelationService.findAllList(input,material,hasCost, searchable.getPage(),CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("查询成功", list);
    }


    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long productId){

        QyMap map= QyMap.NEW();
        long sId=0l;
        if(productId!=null && !productId.equals("null")){
            sId=Long.valueOf(productId);
        }
        Material obj=materialService.findById(sId);
        map.setv("product",obj);
        Searchable searchable= Searchable.newSearchable();
        log.info(productId+">>>>>>>>>>productId"+"33333");
        searchable.addSearchFilter("productId", SearchOperator.eq,obj.getId());
        List<MachiningRelation> machiningRelationList=machiningRelationService.findWithSort(searchable);
        log.info(machiningRelationList.size()+"machiningRelationList");
        map.setv("machiningRelation", JSONUtils.include(new MachiningRelation(), keys));
        if(machiningRelationList!=null && machiningRelationList.size()>0){
            if(machiningRelationList.get(0).getCount()>0){
                map.setv("machiningRelation", JSONUtils.include(machiningRelationList,keys));
            }
        }
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("merchant_machiningRelation:create")
    @PermissionInfo(code = "merchant_machiningRelation:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<QyMap> create(@RequestBody JSONObject json, BindingResult bindingResult){
//        if(machiningRelationService.exists(buildExists(null, "no", machiningRelation.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        log.info("{}",json);
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        machiningRelationService.saveMaterial(json,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<QyMap> show(@ModelAttribute MachiningRelation machiningRelation){
        return ok("查询成功",JSONUtils.include(machiningRelation, keys));
    }


    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute MachiningRelation machiningRelation){
        QyMap map= QyMap.NEW();
        Searchable searchable= Searchable.newSearchable();
        SearchableUtils.newSearchableWithMerchantFilter(searchable);
        initFormDate(map);
        return ok("查询成功",map);
    }



    @RequiresPermissions("merchant_machiningRelation:update")
    @PermissionInfo(code = "merchant_machiningRelation:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<QyMap> update(@ModelAttribute @Valid MachiningRelation machiningRelation, BindingResult bindingResult){
//        if(machiningRelationService.exists(buildExists(null, "no", machiningRelation.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        machiningRelationService.update(machiningRelation);
        return ok("更新成功", null);
    }

    @RequiresPermissions("merchant_machiningRelation:destory")
    @PermissionInfo(code = "merchant_machiningRelation:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/destroy")
    public ResponseResult<QyMap> destroy(Long id){
        machiningRelationService.deleteRelation(id,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("删除成功");
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id, Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            MachiningRelation machiningRelation = machiningRelationService.findById(Long.valueOf(id));
            model.addAttribute(machiningRelation);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        List<MaterialCategory> list=materialCategoryService.buildTree();
        MaterialCategory materialCategory=new MaterialCategory();
        materialCategory.setId(0L);
        materialCategory.setName("所有类别");
        materialCategory.setNo("0");
        list.add(0,materialCategory);
        qyMap.setv("treeData",list);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable=SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchFilter("materialType", SearchOperator.ne, MaterialType.PRODUCT);
        List<Material> materialList = materialService.findWithSort(searchable);
        qyMap.setv("material", Lists.newArrayList());
        if(CollectionUtils.isNotEmpty(materialList)){
            List<QyMap> materials = materialList
                    .stream()
                    .map(item-> QyMap.NEW()
                            .setv("value", "["+item.getNo()+"]"+item.getName())
                            .setv("label", item.getId())
                            .setv("nameValue", item.getName())
                            .setv("goodsSpec", item.getGoodsSpec())
                            .setv("unit", item.getUnit())
                            .setv("state", item.getState())
                            .setv("consumeUnit", item.getConsumeUnit())
                            .setv("orderPriceBom", item.getOrderPriceBom())
                            .setv("consumeRates", item.getConsumeRates())
                            .setv("id",item.getId())
                            .setv("name",item.getName())
                            .setv("no",item.getNo())
                            .setv("code",item.getCode())
                    )
                    .collect(Collectors.toList());
            qyMap.setv("material", materials);
        }
    }

    //获取原料（包含原料和半成品）

    @GetMapping("/getMaterials")
    public ResponseResult<QyMap> getMaterials( String code, Long categoryIds, Searchable searchable){
        searchable.addSearchFilter("materialType", SearchOperator.ne,MaterialType.PRODUCT);
        if(StringUtils.isNotBlank(code)){
            searchable.addSearchFilter(SearchFilterHelper.or(
                    SearchFilterHelper.newCondition("no_like", code),
                    SearchFilterHelper.newCondition("name_like", code),
                    SearchFilterHelper.newCondition("code_like", ","+code)
            ));
        }

        MaterialCategory category = materialCategoryService.findById(categoryIds);
        if(category!=null){
            searchable.addSearchFilter(SearchFilterHelper.or(
                    SearchFilterHelper.newCondition("category.parentIds_like", category.getParentIds()+category.getId()+"/"),
                    SearchFilterHelper.newCondition("category.id_eq", category.getId())
            ));
        }

        QyMap map= QyMap.NEW();
        SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<Material> materials= materialService.findAll(searchable);

        if(CollectionUtils.isNotEmpty(materials.getContent())){
            for (Material material : materials.getContent()) {
                if(com.qinyetech.springstage.core.lang.StringUtils.isNotBlank(material.getCode())){
                    //取一个编码
                    if(material.getCode().indexOf(","+code+",")!=-1){
                        material.setGoodcode(code);
                    }else {
                        material.setGoodcode(material.getCode().substring(1,material.getCode().indexOf(",",2)));
                    }
                    //将编码逗号分隔为数组
                    material.setGoodcodes(org.apache.commons.lang3.StringUtils.split(material.getCode(),","));
                }else {
                    material.setGoodcode("");
                    material.setGoodcodes(null);
                }
            }
        }


        map.setv("materials", JSONUtils.include(materials,new Class[]{State.class},
                "id","no","name","goodsSpec","consumeUnit",
                "orderPriceBom","unit", "consumeRates", "state","goodcode","goodcodes"));

        return ok("初始化成功", map);
    }

}